<template>
  <div class="staDisasterWrap classMain">
    <NavBar
      :title="'灾害统计'"
      :cityName="cityName"
      :areaName="areaName"
      @clicksPopul="clicksPopul"
      :SeveralMenus="'1'"
      :text="'返回'"
    ></NavBar>

    <div class="topTip">
      <divt
        style="position: absolute; width: 90%; left: 7%; height: 65%; top: 11%"
      >
        <div class="topTipLine">
          <span>截止 {{ alarmInitObj.endTime }}，{{ day }}天内，</span>
          <span>生效预警</span>
          <span style="color: blue">{{ totalObj.统计全部 }}</span>
          <span>条</span>
        </div>
        <template v-if="totalObj.统计全部">
          <div class="topTipLine topTipLinetext">
            <span>蓝色预警：</span>
            <span style="color: blue">{{ totalObj.分组统计[0].blue }}</span>
            <span class="topTipLineSpan">条</span>
            <span>黄色预警：</span>
            <span style="color: blue">{{ totalObj.分组统计[0].yellow }}</span>
            <span>条</span>
          </div>
          <div class="topTipLine topTipLinetext">
            <span>橙色预警：</span>
            <span style="color: blue">{{ totalObj.分组统计[0].orange }}</span>
            <span class="topTipLineSpan">条</span>
            <span>红色预警：</span>
            <span style="color: blue">{{ totalObj.分组统计[0].red }}</span>
            <span>条</span>
          </div>
        </template>
      </divt>
    </div>

    <div class="shaiXuan" @click="selectMet">
      <img src="../assets/staDisaster/shaixuan.png" alt="" /> 筛选
    </div>
    <div @click="onClickRight" class="shaiXuan selectBtn1">
      <img src="../assets/staDisaster/yujing.png" alt="" />
      历史预警
    </div>

    <div id="map" class="maps" style="width: 100%; height: 100%"></div>

    <staDisasterSelect
      v-if="showSelect"
      :initObj="alarmInitObj"
      @selectComfirm="selectComfirmMet"
      @detailBack="showSelect = false"
      :showSelect="showSelect"
      @screening="screening"
    >
    </staDisasterSelect>

    <van-popup
      v-model="dwWarnEarthDetailShow"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <detailWarning
        v-if="dwWarnEarthDetailShow"
        :nowClickItem="nowClickItemWarning"
        :textZh="textZh"
        @Disasterstatistics="dwWarnEarthDetailShow = false"
      ></detailWarning>
    </van-popup>

    <comArea
      v-if="showArea"
      @closeEmit="showArea = false"
      :arr="arr1"
      @confirmEmit="confirmEmitMet"
    >
    </comArea>
  </div>
</template>
<script type="text/javascript">
import comArea from "@/components/common/area.vue";
import meteoroStaDisasterApi from "@/service/staDisaster.js";
import staDisasterSelect from "@/components/staDisaster/select.vue";
import meteoroDisasterWarningApi from "@/service/disasterWarning.js";
import dwPicture from "@/components/mixins/dwPicture.js";
import areaInfo from "@/components/common/areaInfo.js";
import detail from "@/components/staDisaster/detail.vue";
import detailWarning from "@/components/disasterWarning/detail.vue";
import map from "@/util/map.js";
import { getItem, setItem } from "../util/storage.js";
import vue from "vue";
import { Dialog } from "vant";
vue.use(Dialog);
export default {
  mixins: [dwPicture],
  data() {
    return {
      showComCityTop: false,
      showSelect: false,

      totalObj: {},
      findAlarmObj: [],
      formatPosiArr: [],
      map: null,
      dwWarnEarthDetailShow: false,
      alarmInitObj: {
        startTime: "",
        endTime: "",
        eventType: "大风",
        severity: "蓝色",
        city: "",
        cnty: "",
      },
      textZh: "",
      nowClickItemWarning: {},
      Marker: [],
      center: [],
      showDetail: false,
      nowClickItem: {},
      day: "",
      location: [],
      cityName: "",
      areaName: "",
      arr1: [],
      showArea: false,
    };
  },
  created() {
    this.center = [112.5659408833, 37.870682192588];
    this.location = getItem("location");
    this.cityName = this.$store.getters.location[1].name;
    this.areaName = this.$store.getters.location[2].name;
    map.init().then((res) => {
      //初始化地图
      this.initMap();

      this.alarmInitObj.endTime = this.$util.getTime();
      this.alarmInitObj.startTime = this.$util.getTime1();

      this.getDay(this.alarmInitObj.endTime, this.alarmInitObj.startTime);
      this.alarmInitObj.city = this.location[1].name;
      this.initTotalAlarmApi(
        "",
        undefined,
        undefined,
        this.alarmInitObj.city,
        "",
        ""
      );
    });
  },

  destroyed: function () {
    this.map.remove();
    // 离开页面生命周期函数
    // this.websocketclose()
  },
  watch: {},
  components: {
    staDisasterSelect,
    detail,
    comArea,
    detailWarning,
  },
  methods: {
    confirmEmitMet(value) {
      var _this = this;
      _this.showArea = false;

      _this.arr = [value];
      _this.$util.Convertlatitude(value).then((result) => {
        _this.center = [result[0], result[1]];
        _this.map.setCenter(_this.center);
        _this.map.setZoom(9);
        _this.cityName = value[1].name;
        _this.areaName = value[2].name;
        _this.arr1 = [value[1].name, value[2].name];
      });
    },
    clicksPopul() {
      this.showArea = true;

      this.arr1 = [this.cityName, this.areaName];
    },
    clickTOPcity() {
      this.showComCityTop = true;
    },
    getDay(endTime, startTime) {
      var date1 = new Date(endTime);
      var date2 = new Date(startTime);

      // 计算相差的时间（单位为毫秒）
      var timeDiff = Math.abs(date2.getTime() - date1.getTime());

      // 计算相差的天数
      this.day = Math.ceil(timeDiff / (1000 * 3600 * 24));
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    onClickRight() {
      this.$router.push({
        name: "staDisasterList",
        params: {
          text: "预警历史",
        },
      });
    },
    onClickHistory() {
      this.$router.push({
        name: "earlyWarnHistory",
        params: {
          city: this.alarmInitObj.city,
        },
      });
    },
    initTotalAlarmApi(value, star, end, city, alarmSeverity, alarmEventtype) {
      // this.$toast.loading({
      //   message: "加载中...",
      //   forbidClick: false,
      //   duration: 0,
      // });
      if (value == undefined) {
        value = this.location[1].name;
      }

      if (star == undefined && end == undefined) {
        var params = {
          alarmSendtimeStart: this.$util.getTime1(),
          alarmSendtimeEnd: this.alarmInitObj.endTime,
        };
      } else {
        var params = {
          alarmSendtimeStart: star,
          alarmSendtimeEnd: end,
          city: city,
          alarmSeverity: alarmSeverity,
          alarmEventtype: alarmEventtype,
        };
      }

      this.alarmInitObj.city = value;
      meteoroStaDisasterApi
        .post_tb_alarm_totalAlarm(params)
        .then((res) => {
          this.totalObj = res;
          this.showComCityTop = false;
        })
        .catch((error) => {});
    },

    selectMet() {
      this.showSelect = true;
      this.showDetail = true;
    },
    screening(params) {
      var _this = this;
      _this.Marker.forEach((it) => {
        it.remove();
      });

      meteoroDisasterWarningApi
        .Earlywarningmap(params)
        .then((res) => {
          _this.getDay(params.endTime, params.startTime);
          _this.initTotalAlarmApi(
            "",
            params.startTime,
            params.endTime,
            params.city,
            params.alarmSeverity,
            params.alarmEventtype
          );
          // 绘制标识图层
          _this.addMarker(_this.map, res);
        })
        .catch((error) => {});
    },
    initMap(location) {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: false,
        duration: 0,
      });
      var _this = this;
      _this.map = new SGMap.Map({
        // 地图绑定的DOM元素ID
        container: "map",
        // 地图样式
        style: "aegis://styles/aegis/Streets-v2",
        // 默认缩放层级
        zoom: 5.5,
        // 地图中心点
        center: _this.center,
        // 地图默认字体
        localIdeographFontFamily: "Microsoft YoHei",
      });
      // 监听地图加载完成事件
      // 地图事件请参考文档 https://map.sgcc.com.cn/products/js-sdk/v3/doc.html#Events
      _this.map.on("load", function (e) {
        _this.$util.initLayerAll("", _this.map);
        _this.$util.searchAll("", _this.map);

        var params = {
          startTime: _this.alarmInitObj.startTime,
          endTime: _this.alarmInitObj.endTime,
        };

        meteoroDisasterWarningApi
          .Earlywarningmap(params)
          .then((res) => {
            // 绘制标识图层
            _this.addMarker(_this.map, res);
          })
          .catch((error) => {});

        //添加监听事件
      });
    },

    // 添加Marker点
    addMarker(map, res) {
      res = res.filter((it) => {
        return it.city !== "无" && it.cnty !== "无";
      });
      const promises = res.map(async (it) => {
        const result = await SGMap.plugin("SGMap.GeocodingTask").then(
            function (res) {
              var geocodingTask = new SGMap.GeocodingTask();
              return geocodingTask.getLocation({
                address: it.city + it.cnty,
                region: "山西",
                isEncode: false,
              });
            }
          );

          it.location = result.location;
          return it;
      });
      (async () => {
        const results = await Promise.all(promises);

        var a = this.$util.getDwType(results);
        for (let i = 0; i < a.length; i++) {
          let item = a[i];

          //   console.log(a[i]);
          var el = document.createElement("div");
          el.className = "marker";

          el.style.backgroundImage =
            "url(" +
            require(`../assets/Earlywarningmap/yujingmap/${item.imageType}-${item.degree}.png`) +
            ")";
          el.style.width = "35px";
          el.style.height = "30px";
          el.setAttribute("data-name", JSON.stringify(item.location));
          el.setAttribute("data-city", JSON.stringify(item.city + item.cnty));
          el.setAttribute(
            "data-cloor",
            JSON.stringify(item.imageType + item.degree)
          );
          // el.setAttribute("data-alarmNote",item.alarmNote);
          // el.setAttribute("data-alarmDescription", item.alarmDescription);
          el.style.backgroundSize = "contain";

          var marker = new SGMap.Marker({
            element: el,
            anchor: "bottom",
          })
            .setLngLat(item.location)

            .addTo(map);
          this.$toast.clear();
          this.Marker.push(marker);

          var _this = this;
          el.addEventListener("click", async (e) => {
            var dataname = e.target.getAttribute("data-name");
            var datacity = e.target.getAttribute("data-city");
            var color = e.target.getAttribute("data-cloor");
            dataname = JSON.parse(dataname);
            datacity = JSON.parse(datacity);
            color = JSON.parse(color);

            var alist = [];

            a.forEach((it) => {
              // console.log(it);
              if (
                it.location.toString() === dataname.toString() &&
                datacity == it.city + it.cnty &&
                color == it.imageType + it.degree
              ) {
                alist = it;
              }
            });

            this.dw = "maps";
            //显示详情
            _this.textZh = "灾害统计";
            _this.nowClickItemWarning = alist;
            _this.dwWarnEarthDetailShow = true;
          });
        }
      })();

      //画marker点
    },
    selectComfirmMet(params) {
      this.showSelect = false;
      let location = `${params.city}${params.cnty}`;
      var _this = this;
      for (let i = 0; i < areaInfo.length; i++) {
        let areaItem = areaInfo[i];
        if (areaItem.location == location) {
          _this.center = areaItem.LongAndLati;
          break;
        }
      }
      this.alarmInitObj = params;
      //请求
      this.findAlarm();
    },
  },
};
</script>
<style type="text/css" lang="less" scoped>
/deep/ .van-nav-bar__content {
  background: #357cff;
}
/deep/ .van-dialog__content {
  width: 100%;
  height: 320px;
  overflow-y: auto;
}
.staDisasterWrap {
  .pageCover();

  .rights {
    color: #fff;
  }
  .maps {
    width: 100%;

    height: 100%;
  }
  .topTip {
    position: absolute;

    width: 345px;
    height: 98px;
    background: #ffffff;
    box-shadow: 0px 0px 15px 0px rgba(191, 191, 191, 0.4);
    border-radius: 10px;
    top: 120px;
    z-index: 999;
    font-size: 13px;
    left: 50%;
    transform: translate(-50%, -50%);
    font-weight: 400;
    color: #101010;
  }
  .topTipLine {
    margin-bottom: 5px;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #101010;
  }
  .topTipLinetext {
    font-size: 13px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #101010;
  }
  .topTipLineSpan {
    margin-right: 10px;
  }
  .selectBtn {
    position: absolute;
    right: 7%;
    top: 10%;
    width: 16%;
    height: 3%;
    font-size: 16px;
    z-index: 9999;
    text-align: center;
    padding: 8px 0px;
    color: #101010;
    box-sizing: border-box;
  }
  .selectBtn0 {
    background-image: url("../assets/staDisaster4.png");
    background-size: 100% 100%;
    background-color: #ececec;
    position: absolute;
    right: 7%;
    top: 27%;
    width: 8%;
    height: 5%;
    text-align: center;
    padding: 8px 0px;
    box-sizing: border-box;
    z-index: 1;
  }

  .shaiXuan {
    position: absolute;
    right: 4%;
    top: 200px;
    z-index: 44;
    width: 55px;
    height: 55px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    background: #357cff;
    box-shadow: 0px 0px 15px 0px rgba(53, 124, 255, 0.6);
    border-radius: 10px;
    font-size: 11px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #ffffff;
    img {
      width: 20px;
      height: 20px;
      margin-bottom: 5px;
    }
  }
  .selectBtn1 {
    top: 270px;
  }
  .history {
    top: 340px;
  }
}
</style>
